import React, { useEffect, useRef, useState } from 'react';
import PageTitle from '@/components/PageTitle';
import { Avatar, Button, Col, Input, Row, Modal, Image, Divider, message } from 'antd';
import { UndoOutlined, UserOutlined, InfoCircleOutlined, UploadOutlined, CloseCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { delCommentList, insertEndDraft, queryByIdWorksInfo } from '@/services/addworks';
import { insertWorksComment, queryByWorkIdComment } from '@/services/addCheck';
import { connect } from 'umi';
import { getdownLoadUrl } from '@/services/file';
import { getAuthority } from '@/utils/authority';

import Cart from './component/Cart';
import EntryInfo from './component/EntryInfo';
import UplodFile from '@/components/FileUpload/UplodFile';

import styles from './index.less';

const { confirm } = Modal;

const AddCheck: React.FC<any> = props => {
  const [inp, setInp] = useState<string | undefined>('');
  const [data, setData] = useState<any[]>([]);
  const [filedata, setFileData] = useState<any[]>([]);
  const [relatfiledata, setRelatFileData] = useState<any[]>([]);
  // 查看词条详情的状态锁
  const [entryInfoStatus, setEntryInfoStatus] = useState<boolean>(false);
  // 判断是图片还是文字的锁
  const [isText, setIsText] = useState<boolean>(true);
  // 词条id
  const [entryId, setEntryId] = useState<any>('');
  const [entryOrderNum, setEntryOrderNum] = useState<number>();
  // 上一个作品的id
  const [prevId, setPrevId] = useState<string | null>(null);
  // 下一个作品的id
  const [nextId, setNextId] = useState<string | null>(null);
  // 释文
  const [printingAnnotations, setPrintingAnnotations] = useState<string>('');
  // 边款
  const [sideStyleAnnotations, setSideStyleAnnotations] = useState<any[]>([]);

  let { location, userData } = props;
  let { id } = location?.query ?? {};
  let seclectRef = useRef<any>(null);

  /**
   * 获取当前作品详情
   */
  useEffect(() => {
    queryByIdWorksInfo({ id }).then(res => {
      if (res?.responseCode == 200) {
        let data: any = res?.data;
        let arr: any[] = data?.worksPicture?.filter((el: any) => el.pictureKey !== 'other');
        setFileData(arr);
        setEntryId(data?.worksInfo?.entryId);
        setEntryOrderNum(data?.worksInfo?.entryOrderNum);
        setPrevId(data?.worksInfo?.beforeWorkInfoId);
        setNextId(data?.worksInfo?.lastWorkInfoId);
        setPrintingAnnotations(data?.worksInfo?.printingAnnotations);
        setSideStyleAnnotations([data?.worksInfo?.sideStyleAnnotationsA, data?.worksInfo?.sideStyleAnnotationsB, data?.worksInfo?.sideStyleAnnotationsC]);
        if (data?.worksInfo?.relatedWorksId) {
          queryByIdWorksInfo({ id: data?.worksInfo?.relatedWorksId }).then(res => {
            if (res?.responseCode == 200) {
              let data: any = res?.data;
              let arr: any[] = data?.worksPicture?.filter((el: any) => el.pictureKey !== 'other');
              setRelatFileData(arr);
            }
          });
        }
      }
    });
    callBack();
  }, []);

  /**
   * 获取原有评论
   */
  const callBack = () => {
    queryByWorkIdComment({ workId: id }).then(res => {
      if (res?.responseCode == 200) {
        setData(res?.data);
        scrollB();
      }
    });
  };

  /**
   * 设置滚动条为最下面
   */
  const scrollB = () => {
    let ref = seclectRef.current;
    ref.scrollTo(0, ref.scrollHeight);
  };

  /**
   * 提交评论
   */
  const sending = (pId?: string) => {
    if (pId) {
      insertWorksComment({
        comments: pId,
        reviewerId: userData?.id,
        workId: id,
        type: 2,
      }).then(res => {
        if (res?.responseCode == 200) {
          setInp('');
          callBack();
        }
      });
      return;
    }
    if (inp && !pId) {
      insertWorksComment({
        comments: inp,
        reviewerId: userData?.id,
        workId: id,
        type: isText ? 1 : 2,
      }).then(res => {
        if (res?.responseCode == 200) {
          setInp('');
          callBack();
        }
      });
    }
  };

  /**
   * 删除当前评论
   */
  const deteleCheckList = (item: any) => {
    confirm({
      title: `是否要删除此条的评审意见？`,
      icon: <ExclamationCircleOutlined />,
      content: '',
      onOk() {
        delCommentList(`${item.commentId}`).then((res: any) => {
          if (res?.responseCode == 200) {
            callBack();
          }
        });
      },
    });
  };

  /**
   * 判断是否是作者权限
   */
  const rc = getAuthority();
  let isUser = rc != 'user';

  return (
    <div className={styles.checkout_demo}>
      <PageTitle
        title={'印稿修改'}
        right={
          <div className="btn-check-dictionary">
            <InfoCircleOutlined />
            <span
              className="btn-check-dictionary-text"
              style={{ marginLeft: '5px', marginRight: '30px' }}
              onClick={() => {
                setEntryInfoStatus(true);
              }}>
              查看词条详情
            </span>

            {!prevId && (
              <span className="btn-check-dictionary-text" style={{ color: '#d9d9d9' }}>
                第一个作品
              </span>
            )}

            {prevId && (
              <span
                className="btn-check-dictionary-text"
                onClick={() => {
                  window.location.href = window.location.protocol + '//' + window.location.host + `/revise/check/addcheck/add?id=${prevId}`;
                }}>
                上一作品
              </span>
            )}

            <Divider type="vertical" className="btn-check-dictionary-text-vertical" />

            {!nextId && (
              <span className="btn-check-dictionary-text" style={{ color: '#d9d9d9' }}>
                最后一个作品
              </span>
            )}

            {nextId && (
              <span
                className="btn-check-dictionary-text"
                onClick={() => {
                  window.location.href = window.location.protocol + '//' + window.location.host + `/revise/check/addcheck/add?id=${nextId}`;
                }}>
                下一作品
              </span>
            )}
          </div>
        }
      />
      <Row gutter={24}>
        <Col span={7}>
          <Cart
            title="印稿初稿"
            content={entryOrderNum ? `词条序号：${entryOrderNum}` : null}
            btn="下载"
            filedata={filedata}
            printingAnnotations={printingAnnotations}
            sideStyleAnnotations={sideStyleAnnotations}
          />
        </Col>
        <Col span={10}>
          <div className="check_demo">
            <div className="title_list">
              <div className="title">
                <span style={{ marginRight: 10 }}>审改意见</span>
                {/*<Button*/}
                {/*  className="btn_red"*/}
                {/*  onClick={() => {*/}
                {/*    insertEndDraft({ id: id }).then((res: any) => {*/}
                {/*      if (res?.data?.responseCode == 200) {*/}
                {/*        window.location.reload();*/}
                {/*      } else {*/}
                {/*        message.error(res?.data?.responseMessage);*/}
                {/*      }*/}
                {/*    });*/}
                {/*  }}*/}
                {/*>*/}
                {/*  审核通过*/}
                {/*</Button>*/}
              </div>
              <div className="down">
                <UndoOutlined twoToneColor="#52c41a" style={{ fontSize: 18 }} onClick={callBack} />
              </div>
            </div>
            <div className="map_list_check" ref={seclectRef}>
              {data?.map((el, index) => (
                <div key={index + 'qweqw1123123_id123_key'} className="list_item">
                  <div className="list_item_left">
                    <div className="list_item_avatar">
                      <Avatar src={el?.portrait ? getdownLoadUrl(el?.portrait) : ''} size={40} icon={<UserOutlined />} />
                      <span className="avater_name">{el?.userName ? el?.userName + '老师' : ''}</span>
                    </div>
                  </div>

                  <div className="list_item_contnet">
                    <CloseCircleOutlined className="close_check" onClick={() => deteleCheckList(el)} />
                    {el.type === 1 ? <span>{el?.comments}</span> : <Image src={el?.comments ? getdownLoadUrl(el?.comments) : ''} />}
                  </div>
                </div>
              ))}
            </div>
            {isUser ? (
              <div className="bottom_inpu">
                <Avatar src={userData?.portrait ? getdownLoadUrl(userData?.portrait) : ''} size={40} icon={<UserOutlined />} />
                <div className="inpue_div">
                  <Input
                    onChange={e => {
                      setIsText(true);
                      setInp(e.target.value);
                    }}
                    value={inp}
                    allowClear
                    size="large"
                    onPressEnter={() => {
                      sending();
                    }}
                  />
                  <Button
                    className="inpue_btn"
                    size="large"
                    onClick={() => {
                      sending();
                    }}>
                    发送
                  </Button>
                </div>
                <div
                  style={{
                    width: '40px',
                    height: '40px',
                    overflow: 'hidden',
                  }}>
                  <UplodFile
                    render={<UploadOutlined className="ant-upload-select-picture-style" />}
                    disabled={false}
                    listType="picture"
                    onChange={(response: any) => {
                      if (response) {
                        setIsText(false);
                        sending(response);
                      }
                    }}
                  />
                </div>
              </div>
            ) : null}
          </div>
        </Col>
        <Col span={7}>
          <Cart title="审改终稿" btn="下载终稿" filedata={relatfiledata} printingAnnotations={printingAnnotations} sideStyleAnnotations={sideStyleAnnotations} />
        </Col>
      </Row>

      <Modal
        className="entry-info-modal"
        maskClosable
        closable={false}
        title="词条详情"
        destroyOnClose
        visible={entryInfoStatus}
        onCancel={() => {
          setEntryInfoStatus(false);
        }}
        footer={
          <Row gutter={24}>
            <Col span={8}></Col>
            <Col span={8}>
              <Button
                onClick={() => {
                  setEntryInfoStatus(false);
                }}>
                关闭
              </Button>
            </Col>
            <Col span={8}></Col>
          </Row>
        }>
        <EntryInfo id={entryId} filedata={filedata} />
      </Modal>
    </div>
  );
};

export default connect(({ login }: any) => ({ userData: login.userData }))(AddCheck);
